import * as echarts from 'echarts';
import { Loading } from '@element-plus/icons-vue';
import MarkdownIt from "markdown-it";

export default {
    name: 'ChatMessage',
    components: {
        Loading
      },
    props: {

        
        sendLoading: {
            type: Boolean,
            required: true,
            default: false
        },
        qaList: {
            type: Array,
            required: true,
            default: () => []
        },
        insight: {
            type: String,
            required: true,
            default: ''
        },
        // resdata: {
        //     type: Array,
        //     required: true,
        //     default: () => []
        // }
    },
    data() {
        return {
            activeTab: 'time',
            md: null,
            localSearchDisplay: '',
            localAnswer: '',
            chartInstances: new Map()
        }
    },
    created() {
        // 初始化markdown-it
            this.md = new MarkdownIt();
    },
    methods: {
        adjustChartWidth(chartId, barCount) {
            const chartContainer = document.getElementById(chartId);
            if (chartContainer) {
              const barWidth = 40; // 每个柱子大约占 40px 宽度
              const totalWidth = barCount * barWidth;
              chartContainer.style.minWidth = `${totalWidth}px`;
            }
          },
        generateChartOptions(data) {
            const baseOption = {
                // animation: false, // 禁用动画避免数据流冲突
                // throttle: 200,    // 节流处理
                title: {
                    text: data.question,
                    left: 'center'
                },
                grid: {
                    top: 60,
                    right: 40,
                    bottom: 60,
                    left: 60,
                    containLabel: true
                }
            };
        
            switch (data.type) {
                case 'scatter':
                    return {
                        ...baseOption,
                        tooltip: {
                            trigger: 'item',
                            formatter: function (params) {
                                return `${params.data[0]}: ${params.data[0].toFixed(2)}%<br/>${params.data[1]}: ${params.data[1].toFixed(2)}%`;
                            }
                        },
                        xAxis: {
                            type: 'value',
                            name: data.options?.scales?.x?.title?.text || 'X轴',
                            nameLocation: 'middle',
                            nameGap: 50,
                            axisLabel: {
                                formatter: '{value}%'
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: data.options?.scales?.y?.title?.text || 'Y轴',
                            nameLocation: 'middle',
                            nameGap: 65,
                            axisLabel: {
                                formatter: '{value}%'
                            }
                        },
                        series: [{
                            type: 'scatter',
                            data: data.data.datasets[0].data.map(item => [
                                typeof item.x === 'number' ? Number(item.x.toFixed(2)) : item.x,
                                typeof item.y === 'number' ? Number(item.y.toFixed(2)) : item.y
                            ]),
                            symbolSize: 10,
                            itemStyle: {
                                color: data.data.datasets[0].backgroundColor || '#87ceeb'
                            }
                        }]
                    };
        
                case 'bar':
                    return {
                        ...baseOption,
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { type: 'shadow' },
                            formatter: function (params) {
                                const value = params[0].value;
                                // 检查值是否存在
                                if (value === undefined || value === null) {
                                    return `${params[0].name}<br/>${params[0].seriesName}: 无数据`;
                                }
                                return `${params[0].name}<br/>${params[0].seriesName}: ${typeof value === 'number' ? value.toLocaleString() : value}${data.options?.scales?.y?.unit || ''}`;
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: data.data.labels,
                            name: data.options?.scales?.x?.title?.text,
                            nameLocation: 'middle',
                            nameGap: 50,
                            axisLabel: {
                                interval: 0,
                                rotate: 30,
                                formatter: function (value) {
                                    return value.length > 10 ? value.substring(0, 10) + '...' : value;
                                }
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: data.options?.scales?.y?.title?.text,
                            nameLocation: 'middle',
                            nameGap: 65,
                            axisLabel: {
                                formatter: function (value) {
                                    if (data.options?.scales?.y?.format === 'percent') {
                                        return value + '%';
                                    } else if (data.options?.scales?.y?.format === 'number') {
                                        return (value / 10000).toFixed(1) + '万';
                                    }
                                    return value;
                                }
                            }
                        },
                        series: [{
                            name: data.data.datasets[0].label || '',
                            type: 'bar',
                            data: data.data.datasets[0].data.map(item =>
                                typeof item === 'object' ? item.y : item
                            ),
                            itemStyle: {
                                color: function (params) {
                                    const colors = data.data.datasets[0].backgroundColor;
                                    return Array.isArray(colors) ? colors[params.dataIndex] : colors || '#87ceeb';
                                }
                            },
                            label: {
                                show: true,
                                position: 'top',
                                formatter: function (params) {
                                    const value = params.value;
                                    if (data.options?.scales?.y?.format === 'percent') {
                                        return value.toFixed(1) + '%';
                                    } else if (data.options?.scales?.y?.format === 'number') {
                                        return (value / 10000).toFixed(1) + '万';
                                    }
                                    return value;
                                }
                            }
                        }]
                    };
        
                case 'line':
                    return {
                        ...baseOption,
                        tooltip: {
                            trigger: 'axis'
                        },
                        xAxis: {
                            type: 'category',
                            data: data.data.labels,
                            name: data.options?.scales?.x?.title?.text,
                            nameLocation: 'middle',
                            nameGap: 50
                        },
                        yAxis: {
                            type: 'value',
                            name: data.options?.scales?.y?.title?.text,
                            nameLocation: 'middle',
                            nameGap: 85
                        },
                        series: data.data.datasets.map(dataset => ({
                            type: 'line',
                            name: dataset.label || '',
                            data: dataset.data.map(item => typeof item === 'object' ? item.y : item),
                            itemStyle: {
                                color: dataset.backgroundColor || '#87ceeb'
                            }
                        }))
                    };
        
                case 'pie':
                    return {
                        ...baseOption,
                        title: {
                            text: data.options.plugins.title.text,
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{b}: {c} ({d}%)'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            top: 'middle'
                        },
                        series: [{
                            type: 'pie',
                            radius: '50%',
                            data: data.data.labels.map((label, index) => ({
                                name: label,
                                value: data.data.datasets[0].data[index],
                                itemStyle: {
                                    color: data.data.datasets[0].backgroundColor?.[index] || '#87ceeb'
                                }
                            }))
                        }]
                    };
        
                default:
                    console.warn('未知的图表类型:', data.type);
                    return baseOption;
            }
        },
       
        
    },
    watch: {
       
        
        
        qaList: {
            
            handler(newList) {
                console.log( "新内容------------",newList);
                newList.forEach((qa) => {
                    if (qa.answer?.type === 'plot' && !qa.answer.loading) {
                        this.$nextTick(() => {
                            const chartDom = document.getElementById(qa.answer.chartId);
                            if (!chartDom) return;

                            let chart = this.chartInstances.get(qa.answer.chartId);
                            if (!chart) {
                                chart = echarts.init(chartDom);

                                // 添加 resize 事件监听器
                                const handleResize = () => {
                                    if (!chart.isDisposed()) {
                                        chart.resize();
                                    }
                                };

                                window.addEventListener('resize', handleResize);
                                // 保存函数引用以便卸载时移除
                                this.handleResize = handleResize;

                                // 保存图表实例
                                this.chartInstances.set(qa.answer.chartId, chart);
                            }

                            // 设置图表配置
                            const option = this.generateChartOptions(qa.answer.content);
                            chart.setOption(option);
                        });
                    }
                });
            },
            deep: true
        }

    },
    beforeUnmount() {
        this.chartInstances.forEach((chart) => {
            if (chart && !chart.isDisposed()) {
                chart.dispose();
            }
        });

        if (this.handleResize) {
            window.removeEventListener('resize', this.handleResize);
            this.handleResize = null;
        }

        this.chartInstances.clear();
    }
}